define(function(require) {

    require('../../../c/base/index');

    require('../../../c/nav/index');

    var firstTime = true;
    var partnerListShow = {};
    var shopTypes = ["","超市","生鲜水果","卤味","烟酒","奶茶","炸鸡","进口商品","蛋糕西点","生禽时蔬","鲜奶吧","零食屋","中式茶点","冷饮站","披萨店","地方特产","糖水店","鲜榨果汁店","全城配送","药品代购","全品类"];
    var addressChoice = {
            "":[],
            "上海市":["黄浦区","卢湾区","徐汇区","长宁区","静安区","普陀区","闸北区","虹口区","杨浦区","宝山区","闵行区","嘉定区","松江区","金山区","青浦区","南汇区","奉贤区","浦东新区","崇明县","城桥镇"],
            "深圳市":["福田区","罗湖区","南山区","宝安区","龙岗区","盐田区"],
            "北京市":["东城区","西城区","崇文区","宣武区","朝阳区","丰台区","石景山区","海淀区","门头沟区","房山区","通州区","顺义区","昌平区","大兴区","平谷区","怀柔区","密云县","延庆县","延庆镇"],
            "广州市":["越秀区","荔湾区","海珠区","天河区","白云区","黄埔区","番禺区","花都区","南沙区","萝岗区","增城市","从化市"],
            "杭州市":["拱墅区","西湖区","上城区","下城区","江干区","滨江区","余杭区","萧山区","建德市","富阳市","临安市","桐庐县","淳安县","千岛湖镇"],
            "苏州市":["金阊区","平江区","沧浪区","虎丘区","吴中区","相城区","常熟市","张家港市","昆山市","吴江市","太仓市"],
            "未开通城市":[]
    };

    var shopJoin = {
        init: function() {
            //初始化菜单选中效果
            $(".fa-circle-o").each(function() {
                if ($(this).parents("a").text() == "商家申请信息") {
                    $(this).parents("a").parents("li").addClass("active");
                }
            });
            this.initDatetimepicker();
            this.initTable();
            this.initValidator();
            this.bindEvent();
            this.doSearch();
        },
        /**
         * 执行查询操作.
         */
        doSearch: function() {
            var fromDate = + new Date($("#fromDate").val()),
                toDate = + new Date($("#toDate").val());

            if(toDate < fromDate) {
                CRM.showDialog('结束时间不能小于开始时间，请重新选择');
                return;
            }
            $("#J_Search").data('bootstrapValidator').validate();
            if ($("#J_Search").data('bootstrapValidator').isValid()) {
                $('#shop_table').DataTable().ajax.reload();
            }
        },
        /*
        判断是否开通进行不同信息提示
        //  */
        // isOpenedCity: function () {
        //     var isOpenedCityObj = CRM.pageConfig;
        //     if ($("#cityChoose").val() == "未开通城市"){
        //         isOpenedCityObj.sZeroRecords = "如需查看未开通城市的申请数据，请选择全部城市，导出表格进行查看";
        //     }
        //     console.log(isOpenedCityObj);
        //     return isOpenedCityObj;
        // },
        // isOpenedCity: function () {
        //     if ($("#cityChoose").val() == "未开通城市"){
        //         console.log("test---");
        //         $(".dataTables_empty").val("如需查看未开通城市的申请数据，请选择全部城市，导出表格进行查看");
        //     }
        // },
        /**
         * 初始化店铺的列表
         */
        initTable: function() {
            var self = this;
            //console.log(isOpenedCity());
            //var oLanguageObj = isOpenedCity();
            $("#shop_table").dataTable({
                "oLanguage": CRM.pageConfig,
                "sScrollX": "100%", //表格的宽度
                "sScrollXInner": "100%", //表格的内容宽度
                "bScrollCollapse": true, //当显示的数据不足以支撑表格的默认的高度时，依然显示纵向的滚动条。(默认是false)
                "bPaginate": true, //是否显示分页
                "bLengthChange": true, //每页显示的记录数
                "bFilter": false, //搜索栏
                "bSort": false, //是否支持排序功能
                "bInfo": true, //显示表格信息
                "bAutoWidth": false, //自适应宽度
                "bServerSide": true, //开启服务端处理
                "sAjaxSource": CRM.getOuterUrl('/member/searchPartnerList.do'),
                "fnInitComplete": function() {
                    this.fnAdjustColumnSizing(true);
                },
                "fnServerData": function(sSource, aoData, fnCallback) {
                    if (firstTime) {
                        firstTime = false;
                        return;
                    }
                    //console.log(aoData);
                    var _url = CRM.getOuterUrl('/member/searchPartnerList.do');
                    var dataString = JSON.stringify({
                        "mobile": $("#mobile").val(),
                        "city": $("#cityChoose").val(),
                        "district": $("#districtChoose").val(),
                        //"city": encodeURIComponent(encodeURIComponent($("#cityChoose").val())),
                        //"district": encodeURIComponent(encodeURIComponent($("#districtChoose").val())),
                        "status": $("#status").val(),
                        "fromDate": $("#fromDate").val(),
                        "toDate": $("#toDate").val(),
                        "pageIndex": aoData[3].value / aoData[4].value + 1,
                        "pageSize": aoData[4].value
                    });
                    // if (!($("#mobile").val() || $("#userid").val())) {
                    //     return;
                    // }
                    CRM.request({
                        "type": 'POST',
                        "url": _url,
                        "dataType": "json",
                        contentType: "application/json; charset=utf-8",
                        xhrFields: {
                            withCredentials: true
                        },
                        "data": dataString,
                        "success": function(req) {
                            if (req.status) {
                                var resultData = CRM.getDataTabelDtaObject();
                                if (req.entry) {
                                    for (var length in req.entry.partnerList){
                                        //console.log( partnerList[req.entry[length].id]);
                                        var idToStr = req.entry.partnerList[length].id + "";
                                        partnerListShow[idToStr] = {};
                                        partnerListShow[idToStr].status = req.entry.partnerList[length].status;
                                        partnerListShow[idToStr].remark = req.entry.partnerList[length].remark;
                                        partnerListShow[idToStr].city = req.entry.partnerList[length].city;
                                    }
                                    //var itemCount = req.entry.length;
                                    //console.log(req.entry.partnerList);
                                    resultData.iTotalDisplayRecords = req.entry.count;
                                        //itemCount;
                                    resultData.iTotalRecords = req.entry.count;
                                        //itemCount;
                                    for (var length in req.entry.partnerList) {
                                        resultData.aaData.push([
                                            //req.entry[length].id,
                                            parseInt(length) + 1,
                                            [req.entry.partnerList[length].city,req.entry.partnerList[length].district],
                                            [req.entry.partnerList[length].applyName,req.entry.partnerList[length].mobile],
                                            [req.entry.partnerList[length].shopName,req.entry.partnerList[length].address],
                                            req.entry.partnerList[length].shopType,
                                            [req.entry.partnerList[length].openingTime,req.entry.partnerList[length].hasBusinessLicense,req.entry.partnerList[length].hasFoodLicense,req.entry.partnerList[length].hasDelivery],
                                            req.entry.partnerList[length].gmtCreate,
                                            [req.entry.partnerList[length].status,req.entry.partnerList[length].id],
                                            {
                                                "id": req.entry.partnerList[length].id,
                                                "remark": req.entry.partnerList[length].remark
                                            }
                                        ])
                                    }
                                } else {
                                    CRM.showDialog(req.message);
                                }
                                fnCallback(resultData);
                            } else {
                                CRM.showDialog(req.message);
                            }
                        }
                    });
                },
                "aaSorting": [
                    [6, "asc"]
                ], //给列表排序 ，第一个参数表示数组 (由0开始)。1 表示Browser列。第二个参数为 desc或是asc
                "aoColumns": [{
                    "sTitle": "序号",
                    "bSortable": true
                }, {
                    "sTitle": "所在城市",
                    "bSortable": true,
                    "mRender": function(data, type, row) {
                        var html = "";
                        var cityRenderStr = data[0].replace(/(.{8})/g,'$1<br>');
                        var disRenderStr = data[1].replace(/(.{8})/g,'$1<br>')
                        html += cityRenderStr + "<br>" + disRenderStr;
                        return html;
                    }
                }, {
                    "sTitle": "申请人信息",
                    "bSortable": true,
                    "mRender": function (data, type, row) {
                        var html = "";
                        var nameRenderStr = data[0].replace(/(.{8})/g,'$1<br>');
                        html += nameRenderStr + "<br>" + data[1];
                        return html;
                    }
                }, {
                    "sTitle": "店铺信息",
                    "bSortable": true,
                    "mRender": function (data, type, row) {
                        var html = "";
                        var addressStr = data[1].replace(/(.{10})/g,'$1<br>');
                        var shopNameStr = data[0].replace(/(.{10})/g,'$1<br>');
                        html += shopNameStr + "<br>" + addressStr;
                        return html;
                    }
                },{
                    "sTitle": "店铺类型",
                    "bSortable": true,
                    "mRender": function (data, type, row) {
                        var _returnStr = "";
                        _returnStr = shopTypes[data];
                        return _returnStr;
                    }
                },{
                    "sTitle": "其他信息",
                    "bSortable": true,
                    "mRender": function(data, type, row) {
                        var _returnBLStr = "";
                        if (data[1] === 1) {
                            _returnBLStr = "有";
                        } else {
                            _returnBLStr = "无";
                        }
                        var _returnFLStr = "";
                        if (data[2] === 1){
                            _returnFLStr = "有";
                        }else {
                            _returnFLStr = "无";
                        }
                        var _returnDeliveryStr = "";
                        if (data[3] === 1){
                            _returnDeliveryStr = "是";
                        }else {
                            _returnDeliveryStr = "否";
                        }
                        var html = "";
                        html += "营业时间: " + data[0] + "<br>" + "营业执照: " + _returnBLStr + "<br>" + "食物流通许可证: " + _returnFLStr + "<br>" + "是否送货上门: " + _returnDeliveryStr;
                        return html;
                    }
                }, {
                    "sTitle": "提交时间",
                    "bSortable": true,
                    "mRender": function (data, type, row) {
                        var _timeStr = "";
                        _timeStr = CRM.format(new Date(data), "yyyy-MM-dd");
                        return _timeStr;
                    }
                },{
                    "sTitle": "处理状态",
                    "bSortable": true,
                    "mRender": function (data, type, row) {
                        var html = "";
                        var isAble = "";
                        var isSelected = ["","","",""];
                        var listStatusId = "listStatus" + data[1];
                        isSelected[data[0]] = "selected";
                        if (isSelected[3].length > 0 || isSelected[2].length > 0) {
                            isAble = "disabled";
                        }
                        html += '<select id="' + listStatusId +'" class="form-control"' + isAble + ' onchange="verifyStatusInfo(' + data[1] + ')"><option value="1"' + isSelected[1] +
                            '>待处理</option><option value="2"'+ isSelected[2] + '>未通过</option><option value="3"' + isSelected[3] +
                            '>已提交</option></select>';
                        return html;
                    }
                },{
                    "sTitle": "备注",
                    "bSortable": true,
                    "mRender": function(data, type, row) {
                        var html = "";
                        var remarkRenderStr = "";
                        //var returnRemarkStr = "";
                        var showRemarkId = "remarkNum" + data.id;
                        if (data.remark){
                            remarkRenderStr = data.remark.replace(/(.{6})/g,'$1<br>');
                            //console.log(remarkRenderStr);
                            //remarkRenderStr = remarkRenderStr.replace(/(.{4})/g,'$1<br>');
                            //returnRemarkStr = '<br>' + '<p id="' + showRemarkId + '" style="font-size: 11px">' + remarkRenderStr + '</p>';
                        }
                        html += '<button type="button" style="padding-left: 0;" class="btn btn-link" onclick="showPartnerInfo(' + data.id + ')">编辑<i class="fa icon-pencil"></i></button>' +
                                '<br>' + '<p id="' + showRemarkId + '" style="font-size: 11px">' + remarkRenderStr + '</p>';
                            //returnRemarkStr;
                        //html += '<div class="btn btn-default" onclick="showDetail(' + data + ')">查看详情</div>';
                        return html;
                    }
                }

                ], //列设置，表有几列，数组就有几项
                "bStateSave": true, //保存状态到cookie *************** 很重要 ， 当搜索的时候页面一刷新会导致搜索的消失。使用这个属性就可避免了
                "sPaginationType": "full_numbers" //分页，一共两种样式，full_numbers和two_button(默认)

            });
        },
        /*
        编辑审核状态及备注
        */
        showPartnerInfo: function (id) {
            //console.log(partnerListShow);
            //console.log(id);
            //console.log(partnerList.id);
            //console.log(partnerListShow[id]);
            var listInfo = partnerListShow[id];
            $("#remark").val(listInfo.remark);
            $("#listId").val(id);
            $("#listStatus").val(listInfo.status);
            $("#partnerListRemark").modal("show");
        },
        // /*
        // 审核保存状态更改
        //  */
        // verifyStatusInfo: function (id) {
        //     var compareCity = (partnerList[id].city).substring(0,(partnerList[id].city).length - 1);
        //     CRM.request({
        //         "type": "POST",
        //         "url": 'http://daily.52shangou.com/shop/city/queryOpenCity',
        //         "contentType": 'application/json',
        //         "data": JSON.stringify({}),
        //         "success": function (req) {
        //             var currentOpenCity = [];
        //             for (var length in req.entry){
        //                 currentOpenCity.push(req.entry.city);
        //             }
        //             if ($.inArray(compareCity,currentOpenCity) > -1){
        //                 //已开通城市
        //             }
        //         }
        //     })
        // },
        /*
        审核状态更改
         */
        verifyStatusInfo: function (id) {
            $("#statusConfirmId").val(id);
            $("#confirm_dialog").modal("show");
        },
        /*
        提交状态更改
         */
        saveStatusInfo: function (id) {
            $(statusNodeStr).attr("disabled", false);
            var statusNodeStr = '#listStatus' + id;
            //console.log(statusNodeStr);
            var statusListId = id;
            //console.log('node是' + node);
            //console.log($('#' + node));
            var statusListStatus = $(statusNodeStr).val();
            //console.log(statusListStatus);
            var statusListRemark = partnerListShow[id].remark;
            //if (statusListStatus == 3){}
            //$("#confirm_dialog").modal("show");
            CRM.request({
                "type": "POST",
                "url": CRM.getOuterUrl("/member/updatePartnerInfo.do"),
                "dataType": "json",
                contentType: "application/json; charset=utf-8",
                "data": JSON.stringify({
                    "id": statusListId,
                    "status": statusListStatus,
                    "remark": statusListRemark
                }),
                "success": function (req) {
                    if (statusListStatus == 3){
                        //$(statusNodeStr).attr("disabled", true);
                        //$('#shop_table').DataTable().ajax.reload();
                        if (req.status) {
                            $(statusNodeStr).attr("disabled", true);
                            CRM.showDialog("状态更改成功");
                        } else {
                            CRM.showDialog("该商户所在城市没有开通服务，不能改为已提交");
                        }
                    } else if (statusListStatus == 2) {
                        //$('#shop_table').DataTable().ajax.reload();
                        $(statusNodeStr).attr("disabled", true);
                        CRM.showDialog("状态更改成功");
                    } else {
                        CRM.showDialog("状态更改成功");
                    }
                }
                // "error": function (req) {
                //     if (statusListStatus == 3){
                //         CRM.showDialog("该商户所在城市没有开通服务，不能改为已提交");
                //     }
                // }
            })
        },
        /*
        保存备注编辑
         */
        saveInfo: function () {
            var listId = $("#listId").val();
            var listStatus = $("#listStatus").val();
            var listRemark = $("#remark").val().trim();
            var currentRemarkNode = "#remarkNum" + listId;
            var currentShowRemark = listRemark.replace(/(.{5})/g,'$1<br>');
            console.log(currentRemarkNode);
            CRM.request({
                "type": "POST",
                "url": CRM.getOuterUrl("/member/updatePartnerInfo.do"),
                "dataType": "json",
                contentType: "application/json; charset=utf-8",
                "data": JSON.stringify({
                    "id": listId,
                    "status": listStatus,
                    "remark": listRemark
                }),
                "success": function (req) {
                    //$('#shop_table').DataTable().ajax.reload();
                    console.log(currentShowRemark);
                    partnerListShow[listId].remark = listRemark;
                    $(currentRemarkNode).html(currentShowRemark);
                    if (req.status) {
                        CRM.showDialog("保存成功！");
                    } else {
                        CRM.showDialog(req.message);
                    }
                }
            });
        },
        /**
         * 表单验证初始化
         */
        initValidator: function() {
            $('#J_Search').bootstrapValidator({
                message: '输入错误',
                feedbackIcons: {
                    //valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove'
                    //validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    mobile: {
                        message: 'error',
                        validators: {
                            phone: {
                                country: 'CN',
                                message: '请输入正确的电话格式'
                            }
                        }
                    }
                }
            });
            // $("#remark").bootstrapValidator({
            //     message: '输入错误',
            //     feedbackIcons: {
            //         valid: 'glyphicon glyphicon-ok',
            //         invalid: 'glyphicon glyphicon-remove',
            //         validating: 'glyphicon glyphicon-refresh'
            //     },
            //     fields: {
            //         remark: {
            //             message: '输入内容有误',
            //             validators: {
            //                 stringLength: {
            //                     max: 100,
            //                     message: '长度限制为100字'
            //                 }
            //             }
            //         }
            //     }
            // })
        },
        /*
        导出文件
         */
        exportFile: function () {
            $("#J_Search").data('bootstrapValidator').validate();
            if ($("#J_Search").data('bootstrapValidator').isValid()) {
                CRM.request({
                    "type": "GET",
                    "url": CRM.getOuterUrl("/member/exportPartnerList.do"),
                    "dataType": "json",
                    contentType: "application/json; charset=utf-8",
                    "data": {
                        "mobile": $("#mobile").val(),
                        "city": $("#cityChoose").val(),
                        "district": $("#districtChoose").val(),
                        "status": $("#status").val(),
                        "fromDate": $("#fromDate").val(),
                        "toDate": $("#toDate").val()
                    },
                    "success": function (req) {
                        //if (req.status){
                        CRM.showDialog(req.message);
                        // } else {
                        //     alert(CRM.getOuterUrl("/member/exportPartnerList.do") + '?mobile=' + $("#mobile").val() +
                        //         '&city=' + $("#cityChoose").val() + '&district=' + $("#districtChoose").val() +
                        //         '&status=' + $("#status").val() + '&fromDate=' + $("#fromDate").val() +
                        //         '&toDate=' + $('#toDate').val());
                        //
                        // }
                    },
                    "error": function () {
                        location.href = CRM.getOuterUrl("/member/exportPartnerList.do") + '?mobile=' + $("#mobile").val() +
                            '&city=' + $("#cityChoose").val() + '&district=' + $("#districtChoose").val() +
                            '&status=' + $("#status").val() + '&fromDate=' + $("#fromDate").val() +
                            '&toDate=' + $('#toDate').val();
                    }
                });
            }
        },
        /*
        初始化时间选择器
         */
        initDatetimepicker : function() {
            $('.form_date').datetimepicker({
                language:  'zh-CN',
                weekStart: 1,
                todayBtn:  1,
                autoclose: 1,
                todayHighlight: 1,
                startView: 2,
                minView: 2,
                forceParse: 0
            });
            // $('#toDate').datetimepicker({
            //     language:  'zh-CN',
            //     weekStart: 1,
            //     todayBtn:  1,
            //     autoclose: 1,
            //     todayHighlight: 1,
            //     startView: 2,
            //     minView: 2,
            //     forceParse: 0
            // });
        },
        /*
        级联选择
         */
        cityToDistrict: function () {
            var currentCity = $("#cityChoose").val();
            var currentArea = addressChoice[currentCity];
            for (var i = 0;i < currentArea.length;i++){
                var opts = document.createElement("option");
                opts.innerHTML = currentArea[i];
                opts.value = currentArea[i];
                $("#districtChoose").append(opts);
            }
        },
        bindEvent: function() {
            var self = this;
            $("#search_btn").on('click', function() {
                //console.log(isOpenedCity());
                if ($("#cityChoose").val() == '未开通城市') {
                    CRM.showDialog("如需查看未开通城市的申请数据，请选择全部城市进行查看")
                }
                self.doSearch();
                //self.isOpenedCity();
            });
            $("#export_btn").on('click', function () {
                self.exportFile();
            });
            $("#cityChoose").on('change', function () {
                // if ($(this).val() == '未开通城市') {
                //     CRM.showDialog("如需查看未开通城市的申请数据，请选择全部城市，导出表格进行查看。")
                // }
                var initSelectHtml = '<option value="" selected>全部</option>';
                $("#districtChoose").html(initSelectHtml);
                self.cityToDistrict();
            });
            $("#confirm").on('click', function () {
                var confirmID = $("#statusConfirmId").val();
                //console.log(confirmID);
                self.saveStatusInfo(confirmID);
            });
            $("#noConfirm").on('click', function () {
                $('#shop_table').DataTable().ajax.reload();
            });
            // $("#cityChoose").on('change', function () {
            //     if ($(this).val() == '未开通城市') {
            //         CRM.showDialog("如需查看相关数据，请选择全部城市，导出表格进行查看。")
            //     }
            // })
        }
    };

    window.doSearch = $.proxy(shopJoin.doSearch, shopJoin);
    window.showDetail = $.proxy(shopJoin.showDetail, shopJoin);
    window.saveInfo = $.proxy(shopJoin.saveInfo, shopJoin);
    window.showPartnerInfo = $.proxy(shopJoin.showPartnerInfo, shopJoin);
    window.saveStatusInfo = $.proxy(shopJoin.saveStatusInfo, shopJoin);
    window.verifyStatusInfo = $.proxy(shopJoin.verifyStatusInfo, shopJoin);
    //window.isOpenedCity = $.proxy(shopJoin.isOpenedCity, shopJoin);

    shopJoin.init();
});
